import os
import json
from typing import Dict, List, Union
import logging
from datetime import datetime

class FileHandler:
    def __init__(self, base_path: str = 'data', max_records: int = 1000):
        """初始化文件处理器
        
        Args:
            base_path: 文件存储的基础路径
            max_records: 最大记录数量
        """
        self.base_path = base_path
        self.max_records = max_records
        self._ensure_directory_exists()
    
    def _ensure_directory_exists(self) -> None:
        """确保存储目录存在"""
        if not os.path.exists(self.base_path):
            os.makedirs(self.base_path)
    
    def read_ip_data(self) -> Union[List, None]:
        """从文件读取 JSON 数据"""
        try:
            file_path = os.path.join(self.base_path, 'ip_records.json')
            if not os.path.exists(file_path):
                return None
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            logging.error(f"读取文件失败: {str(e)}")
            return None
    
    def append_ip_data(self, ip_data: Dict) -> bool:
        """将IP数据追加到JSON文件中"""
        try:
            file_path = os.path.join(self.base_path, 'ip_records.json')
            
            # 读取现有数据
            existing_data = []
            if os.path.exists(file_path):
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        existing_data = json.load(f)
                except json.JSONDecodeError:
                    existing_data = []
            
            # 确保existing_data是列表
            if not isinstance(existing_data, list):
                existing_data = []
            
            # 添加新数据
            existing_data.append(ip_data)
            
            # 限制记录数量
            if len(existing_data) > self.max_records:
                existing_data = existing_data[-self.max_records:]
            
            # 写回文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(existing_data, f, ensure_ascii=False, indent=2)
            
            return True
            
        except Exception as e:
            logging.error(f"追加IP数据失败: {str(e)}")
            return False 